import React, { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { Space, Swiper, Image, Tabs, Grid, Ellipsis, Tag, NavBar, InfiniteScroll } from "antd-mobile";
import { FireFill } from "antd-mobile-icons";
import request from "@/utils/request";

function Rank() {
    // 真标签
    const tabs = [
        { title: "推荐榜", key: "all" },
        { title: "热度榜", key: "hot" },
        { title: "新作榜", key: "new" },
    ];

    const [key, setKey] = useState("");
    const [datalist, setDatalist] = useState([]);
    const [page, setPage] = useState(1);
    const [newDatalist, setNewDatalist] = useState([]);
    const [SwipeData, setSwipeData] = useState([]);
    const navigate = useNavigate();
    // 初始状态不能设置为true，否则前10条数据会被吞掉
    const [hasMore, setHasMore] = useState(false);
    const [loading, setLoading] = useState(false);

    const back = () => {
        navigate(-1);
    };

    // 跳转到详情页
    const gotoDetail = (id) => {
        navigate("/detail?id=" + id);
    };
    // 刷新工具人
    const getData = async () => {
        const { data } = await request.get("/books/list");
        setDatalist(data);
    };

    // 轮播图
    const getSwiper = async () => {
        const { data } = await request.get("/swiper/list2");
        setSwipeData(data.data);
    };
    // 下面渲染的数据
    const getNewData = async () => {
        const { data } = await request.get("/books/list");
        setNewDatalist(data.data[0]);
    };

    const changeKey = (key) => {
        setKey(key);
    };

    // tab改变渲染更新数据
    useEffect(() => {
        getData(); //起到刷新的作用
        if (key === "hot") {
            setNewDatalist(
                newDatalist.sort((a, b) => {
                    return a.hot - b.hot;
                })
            );
        } else if (key === "all") {
            setNewDatalist(
                newDatalist.sort((a, b) => {
                    return a.id - b.id;
                })
            );
        } else {
            setNewDatalist(
                newDatalist.sort((a, b) => {
                    return b.timer - a.timer;
                })
            );
        }
    }, [key]);

    // 加载完先请求一次，目的是为了不让初始页面变空白
    useEffect(() => {
        getData();
        getNewData(); //下面渲染数据
        getSwiper(); //轮播图数据
    }, []);

    const loadMore = () => {
        // 节流：非加载中状态且还有未加载完的数据时才发起请求
        if (hasMore && !loading) {
            setPage(page + 1);
            setLoading(true);
        }
    };
    // 负责无限滚动请求数据
    const getData2 = async () => {
        const { data } = await request.get("/books/list", {
            params: {
                page,
            },
        });
        const newDatalist1 = [...newDatalist, ...data.data[0]];
        setNewDatalist(newDatalist1);
        setHasMore(newDatalist1.length < 50);
        setLoading(false);
    };
    // 页数改变才请求数据
    useEffect(() => {
        getData2();
    }, [page]);

    const items = SwipeData.map((index) => (
        <Swiper.Item key={index.id}>
            <div
                style={{
                    height: 145,
                    display: "flex",
                    justifyContent: "center",
                    alignItem: "center",
                }}
            >
                <Image
                    src={index.swiper}
                    style={{ "--height": "100%", "--width": "100%" }}
                    onClick={gotoDetail.bind(null, index.id)}
                />
            </div>
        </Swiper.Item>
    ));
    return (
        <div>
            <NavBar
                onBack={back}
                style={{
                    position: "fixed",
                    top: 0,
                    left: 0,
                    width: "100%",
                    padding: 0,
                    backgroundColor: "rgba(255, 255, 255, 0.950)",
                    zIndex: 99,
                }}
            >
                <b>TOP50</b>排行榜
            </NavBar>
            <Swiper
                slideSize={100}
                loop
                stuckAtBoundary={false}
                autoplay
                direction="vertical"
                style={{ "--height": "145px", marginTop: "32px" }}
                indicator={() => null}
            >
                {items}
            </Swiper>

            <Tabs
                defaultActiveKey={"all"}
                onChange={changeKey}
                style={{ "--active-title-color": "#ff3141", "--active-line-color": "#ff3141" }}
            >
                {tabs.map((item_tabs) => (
                    <Tabs.Tab title={item_tabs.title} key={item_tabs.key} activeKey={item_tabs.key}>
                        <div>
                            <Grid columns={1} gap={8}>
                                {newDatalist.map((item, index) => (
                                    <Grid.Item key={item.id} style={{ display: "flex" }}>
                                        <div style={{ flex: 1 }}>
                                            <Image
                                                src={item.pic}
                                                height="100%"
                                                width="100%"
                                                onClick={gotoDetail.bind(null, item.id)}
                                            />
                                        </div>
                                        <div style={{ marginLeft: 20, flex: 2 }}>
                                            <div
                                                style={{
                                                    display: "flex",
                                                    justifyContent: "space-between",
                                                }}
                                            >
                                                <h3>{item.book}</h3>
                                                <p
                                                    style={{
                                                        fontWeight: "bold",
                                                        color:
                                                            index + 1 === 1
                                                                ? "red"
                                                                : index + 1 === 2
                                                                ? "green"
                                                                : index + 1 === 3
                                                                ? "blue"
                                                                : "black",
                                                    }}
                                                >
                                                    <FireFill />
                                                    NO.{index + 1}
                                                </p>
                                            </div>
                                            <div
                                                style={{
                                                    color: "#f00",
                                                    marginTop: 0,
                                                }}
                                            >
                                                <Space>
                                                    <span style={{ margin: 0 }}>作者：{item.author}</span>
                                                    <Tag color="orange" fill="outline">
                                                        {item.booktype}
                                                    </Tag>
                                                </Space>
                                            </div>
                                            <Ellipsis content={item.brief} rows={3}></Ellipsis>
                                        </div>
                                    </Grid.Item>
                                ))}
                            </Grid>
                        </div>
                        <InfiniteScroll loadMore={loadMore} hasMore={hasMore} />
                    </Tabs.Tab>
                ))}
            </Tabs>
        </div>
    );
}

export default Rank;
